package cn.fl.dk.web.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.service.ICapOverdueInfoService;
import cn.fl.dk.facade.api.IDkBillDtlApiService;
import cn.fl.dk.facade.condition.DkBillDtlQC;
import cn.fl.dk.facade.condition.DkPaySchMQC;
import cn.fl.dk.facade.constant.DkBillDtlConstant;
import cn.fl.dk.facade.constant.DkContractLogConstant;
import cn.fl.dk.facade.constant.DkQuestneLogConstant;
import cn.fl.dk.facade.constant.DkRuleInfoConstant;
import cn.fl.dk.facade.dto.DkBillDtlDTO;
import cn.fl.dk.web.service.IDkBillDtlService;
import cn.fl.dk.web.service.IDkBillInfoService;
import cn.fl.dk.web.service.IDkRuleInfoService;
import cn.fl.dk.web.transform.DkBillDtlVOTransform;
import cn.fl.dk.web.vo.DkBillDtlVO;
import cn.fl.dk.web.vo.DkBillInfoVO;
import cn.fl.dk.web.vo.DkPaySchMVO;
import cn.fl.dk.web.vo.DkRuleInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysDictionaryService;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 垫款单明细表 控制层
 */
@Controller
@RequestMapping("/dk/dkbilldtl")
public class DkBillDtlController extends BaseController {

    //private static final Logger logger = LoggerFactory.getLogger(DkBillDtlController.class);

    /**
     * DkBillDtl 服务层BEAN
     */
    @Autowired
    private IDkBillDtlService dkBillDtlService;
    @Autowired
    private IDkBillInfoService dkBillInfoService;
    @Autowired
    private IDkRuleInfoService dkRuleInfoService;
    @Autowired
    private ISysDictionaryService sysDictionaryService;
    @Autowired
    private ICapOverdueInfoService capOverdueInfoService;
    @Autowired
	private IDkBillDtlApiService dkBillDtlApiService;
    
    /**
     * 到执行页面
     */
    @RequestMapping(value = "/toDkBillDtlZx.do", method = {RequestMethod.GET})
    public ModelAndView todkBillDtlZx(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("toListPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlZx");
        String billId = request.getParameter("billId");
        if(StringUtils.isNotEmpty(billId)){
            DkBillInfoVO dkBillInfoVO = dkBillInfoService.selectById(Long.valueOf(billId));
            DkRuleInfoVO dkRuleInfoVO = dkRuleInfoService.selectById(dkBillInfoVO.getRuleId());
            view.addObject("dkBillInfoVO",dkBillInfoVO);
            view.addObject("dkRuleInfoVO",dkRuleInfoVO);
        }

        return view;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("toListPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlList");
        String billId = request.getParameter("billId");
        view.addObject("billId",billId);

        List<String> codeGrpCdList = new ArrayList<>();
        codeGrpCdList.add(DkBillDtlConstant.CALC_RST_CD);//垫款单明细-垫款测算结果
        codeGrpCdList.add(DkBillDtlConstant.DTL_STS_CD);//垫款单明细-垫款明细状态
        codeGrpCdList.add(DkQuestneLogConstant.GROUP_CD_QTN_RST_CD);//问卷结果
        codeGrpCdList.add(DkContractLogConstant.SIGN_STS_CD);//合同签署状态
        Map<String, List<KeyValueVO>> stsCdList = sysDictionaryService.getMultiKvList(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
        view.addObject("stsCdList",stsCdList);
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载新增").setLogOperType(LogOperEnum.REQ).setKeys("toAddPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlAdd");
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(ModelAndView view ,Long billId,@RequestParam(required = false,defaultValue = "0") String viewFlag) {
        BaseLogUtils.newLogger("加载修改页面").setLogOperType(LogOperEnum.REQ).setKeys("toModifyPage",CurrentThreadContext.getCurrentUserName()).info();
        view.addObject("viewFlag",viewFlag);
        view.addObject("billId",billId);
        if(StringUtils.isNotEmpty(billId)){
            DkBillInfoVO dkBillInfoVO = dkBillInfoService.selectById(Long.valueOf(billId));
            DkRuleInfoVO dkRuleInfoVO = dkRuleInfoService.selectById(dkBillInfoVO.getRuleId());
            view.addObject("dkBillInfoVO",dkBillInfoVO);
            view.addObject("dkRuleInfoVO",dkRuleInfoVO);
        }
        view.setViewName("dk/dkBillDtl/dkBillDtlMd");
        return view;
    }

    /**
     * 明垫列表
     * @param dkCountMin 必填
     * @param dkCountMax 必填
     * @param overdueDayMin 必填
     * @param overdueDayMax 必填
     * @return
     */
    @RequestMapping("/initMingDianPaySchList.do")
    @ResponseBody
    public ListPageVO<DkPaySchMVO> initMingDianPaySchList(@RequestParam(required = false) String lsDtStart,
                                                          @RequestParam(required = false) String lsDtEnd,
                                                          @RequestParam Long dkCountMin,
                                                          @RequestParam Long dkCountMax,
                                                          @RequestParam Long overdueDayMin,
                                                          @RequestParam Long overdueDayMax,
                                                          @RequestParam Long fundRasInsId,int page,int pagesize){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        DkPaySchMQC condition = new DkPaySchMQC();
        pager.setCondition(condition);
        if(dkCountMin != -1l){
            condition.setDkCountMin(dkCountMin);
        }
        if(dkCountMax != -1l){
            condition.setDkCountMax(dkCountMax);
        }
        if(overdueDayMin != -1l){
            condition.setOverdueDayMin(overdueDayMin);
        }
        if(overdueDayMax != -1l){
            condition.setOverdueDayMax(overdueDayMax);
        }
        if(StringUtils.isNotEmpty(lsDtStart)){
            condition.setLsDtStart(lsDtStart);
        }
        if(StringUtils.isNotEmpty(lsDtEnd)){
            condition.setLsDtEnd(lsDtEnd);
        }
        condition.setFundRasInsId(fundRasInsId);
        pager =  this.dkBillDtlService.selectMingDianPaySchMListPage(pager);
        List<DkPaySchMVO> resultList = (List<DkPaySchMVO>) pager.getResultList();
        return new ListPageVO<>(resultList,pager.getTotalCount());
    }

    /**
     * 明垫详情页面列表初始化
     * @param dkCountMin
     * @param dkCountMax
     * @param overdueDayMin
     * @param overdueDayMax
     * @param billId
     * @return
     */
    @RequestMapping("/initViewMingDianPaySchList.do")
    @ResponseBody
    public ListPageVO<DkBillDtlDTO> initViewMingDianPaySchList(@RequestParam Long dkCountMin,
                                                          @RequestParam Long dkCountMax,
                                                          @RequestParam Long overdueDayMin,
                                                          @RequestParam Long overdueDayMax ,
                                                          @RequestParam Long billId,
                                                               @RequestParam Long fundRasInsId){
        DkBillDtlQC qc = new DkBillDtlQC();
        qc.setBillId(billId);
        qc.setIsDel(0);
        List<DkBillDtlDTO> dkBillDtlDTOS = this.dkBillDtlService.searchDkBillDtlList(qc);
        List<Long> paySchIdList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(dkBillDtlDTOS)){
            for (DkBillDtlDTO dkBillDtlDTO : dkBillDtlDTOS) {
                paySchIdList.add(dkBillDtlDTO.getPaySchId());
            }
        }
        
        return new ListPageVO<>(dkBillDtlDTOS,dkBillDtlDTOS.size());
    }
    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载例子详细页面").setLogOperType(LogOperEnum.REQ).setKeys("toDetailPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlDetail");
        view.addObject("id", id);
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("initList",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String billId = request.getParameter("billId");//垫款单id
        String qtnRstCd = request.getParameter("qtnRstCd");//问卷结果
        String calcRstCd = request.getParameter("calcRstCd");//垫款测算结果
        String signStsCd = request.getParameter("signStsCd");//合同签署状态
        String dtlStsCd = request.getParameter("dtlStsCd");//垫款状态
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        DkBillDtlQC qc = new DkBillDtlQC();
        if (StringUtils.isNotEmpty(billId)) {
            qc.setBillId(Long.valueOf(billId));
        }
        if (StringUtils.isNotEmpty(qtnRstCd)) {
            qc.setQtnRstCd(qtnRstCd);
        }
        if (StringUtils.isNotEmpty(calcRstCd)) {
            qc.setCalcRstCd(calcRstCd);
        }
        if (StringUtils.isNotEmpty(signStsCd)) {
            qc.setSignStsCd(signStsCd);
        }
        if (StringUtils.isNotEmpty(dtlStsCd)) {
            qc.setDtlStsCd(dtlStsCd);
        }
        page.setCondition(qc);

        Pager pager = this.dkBillDtlService.searchListPage(page);
        List<DkBillDtlVO> list = DkBillDtlVOTransform.toVOList((List<DkBillDtlDTO>) pager.getResultList());
        ListPageVO<DkBillDtlVO> listPage = new ListPageVO<DkBillDtlVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 查询 : 
     * 		1、未垫款，合同已签的数据 
     * 		2、查询：
     * 		测试结果是 ： 2：赎回
     * 		规则的赎回执行是：1.标记赎回
     *      垫款明细状态： 0空（未垫款）
     * @Title: searchList
     * @param @param request
     * @param @param response
     * @param @return
     * @author gaoyongfei
     * @date 2018-7-3 下午6:16:45
     * @return Object 
     * @throws
     */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/searchList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object searchList(HttpServletRequest request, HttpServletResponse response) {
        String billId = request.getParameter("billId");//垫款单id
        List<DkBillDtlDTO> lists =new ArrayList<DkBillDtlDTO>();
		if (StringUtils.isEmpty(billId)) {
			return null;
		}
		/**
		 * 1、查询：
		 * 		垫款明细状态： 0空（未垫款）
		 * 		合同 ：1签署成功
		 */
		DkBillDtlQC qc = new DkBillDtlQC();
		qc.setBillId(new Long(billId));
		qc.setDtlStsCd(DkBillDtlConstant.DTL_STS_CD_0);
		qc.setSignStsCd(DkBillDtlConstant.DTL_SIGNSTSCD_1);
		List<DkBillDtlDTO> lists1 = this.dkBillDtlService.searchlListByContractLog(qc);
		
        /**
         * 2、查询：
         * 		测试结果是 ： 2：赎回
         * 		规则的赎回执行是：1.标记赎回
         *      垫款明细状态： 0空（未垫款）
         */
        List<DkBillDtlDTO> lists2 = null;
		DkBillInfoVO billInfoVO = dkBillInfoService.selectById(Long.valueOf(billId));
		DkRuleInfoVO ruleInfoVO = dkRuleInfoService.selectById(billInfoVO.getRuleId());
        if(DkRuleInfoConstant.DK_RULE_RANSOM_EXECCD_1.equals(ruleInfoVO.getRansomExecCd())){
        	DkBillDtlQC qc1 = new DkBillDtlQC();
        	qc1.setBillId(new Long(billId));
        	qc1.setDtlStsCd(DkBillDtlConstant.DTL_STS_CD_0);
        	qc1.setCalcRstCd(DkBillDtlConstant.CALC_RST_CD_2);
			lists2 = dkBillDtlApiService.searchDkBillDtlList(qc1);
		}
        
        // lists1 中的数据在 lists中没有，就加到 lists中
        List<DkBillDtlDTO> resultLists =new ArrayList<DkBillDtlDTO>();
        if (CollectionUtils.isNotEmpty(lists1)) {  
            List<String> arr = new ArrayList<String>();
            if(CollectionUtils.isNotEmpty(lists2)){
            	for(DkBillDtlDTO dtlDTO : lists1){
                	arr.add(dtlDTO.getId()+"");
                }
                for(DkBillDtlDTO dtlDTO2 : lists2){
                	if(!arr.contains(dtlDTO2.getId()+"")){
                		lists1.add(dtlDTO2);
                	}
            	}
            }
            lists.addAll(lists1);
        }else if(CollectionUtils.isEmpty(lists1) && CollectionUtils.isNotEmpty(lists2)){
        	lists.addAll(lists2);
        }
        
    	/** 
    	 * 3、执行前：更新实际垫款金额 
    	 */
        this.dkBillDtlService.handleAfterUpdateInfo(lists);
		for(DkBillDtlDTO dto : lists){
			dto.setOverdueAmountYuan(DecimalUtils.convertFenToYuan(dto.getOverdueAmount()));//逾期金额(元)
			dto.setActualRedeemAmtYuan(DecimalUtils.convertFenToYuan(dto.getActualRedeemAmt()));
			dto.setEstimateRedeemAmtYuan(DecimalUtils.convertFenToYuan(dto.getEstimateRedeemAmt()));
		}
		Pager page = new Pager();
        page.setCurrentPage(1);
    	page.setEveryPage(lists.size());
    	ListPageVO<DkBillDtlVO> listPage = new ListPageVO<DkBillDtlVO>(DkBillDtlVOTransform.toVOList(lists), lists.size());
    	return listPage;
    }
		
	@RequestMapping(value = "/countAmountByContractLog.do", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Object countAmountByContractLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("countAmountByContractLog").setLogOperType(LogOperEnum.REQ).setKeys("countAmountByContractLog",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        String billId = request.getParameter("billId");//垫款单id
		
	 	Map<String, String> map = new HashMap<String, String>();
	 	map.put("isSuccess", "0");
		if (StringUtils.isEmpty(billId)) {
			return null;
		}
		
		int dfPayCount = 0;
        int shPayCount = 0;
        long dfPayAmt = 0;
        long shPayAmt = 0;
        try {
        	DkBillDtlQC qc = new DkBillDtlQC();
        	qc.setBillId(new Long(billId));
			List<DkBillDtlDTO> lists = this.dkBillDtlService.searchlListByContractLog(qc);
	        if (CollectionUtils.isEmpty(lists)) {
	        	return null;
	        }
	       
	        for(DkBillDtlDTO entity : lists){
	        	if("1".equals(entity.getCalcRstCd())){// 垫付
	        		dfPayCount = dfPayCount + 1;
	        		dfPayAmt = dfPayAmt + entity.getActualRedeemAmt().longValue();
	        		entity.getActualRedeemAmt();
	        	}else if("2".equals(entity.getCalcRstCd())){// 赎回
	        		shPayCount = shPayCount + 1;
	        		shPayAmt = shPayAmt + entity.getActualRedeemAmt().longValue();
	        	}
	        }
	        
	        map.put("dfPayCount", dfPayCount+"");
	        map.put("shPayCount", dfPayCount+"");
	        map.put("dfPayAmt", dfPayCount+"");
	        map.put("shPayAmt", dfPayCount+"");
	        map.put("isSuccess", "1");
        } catch (Exception ex) {
        	map.put("isSuccess", "0");
        }
        
        return map;
    }
	 
    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("新增对象").setLogOperType(LogOperEnum.REQ).setKeys("add",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        DkBillDtlVO entity = null;
        try {
            entity = new DkBillDtlVO();
            Long id = this.dkBillDtlService.add(entity);
            result.setData(id);
            BaseLogUtils.newLogger("新增数据").setLogOperType(LogOperEnum.REQ).setKeys("add","DkBillDtlVO=" + JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName()).info();
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("新增对象失败").setLogOperType(LogOperEnum.REQ).setKeys("add","name="+name,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newLogger("新增对象失败").setLogOperType(LogOperEnum.REQ).setKeys("add","name="+name,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0099);
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("修改对象").setLogOperType(LogOperEnum.REQ).setKeys("modify",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.newLogger("修改数据,主键不存在").setLogOperType(LogOperEnum.REQ).setKeys("modify",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
            return result;
        }
        DkBillDtlVO entity = null;
        try {
            entity = new DkBillDtlVO();
            entity.setId(Long.valueOf(id));
            boolean success = this.dkBillDtlService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.newLogger("修改失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","DkBillDtlVO="+JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName()).info();
            }
            BaseLogUtils.newLogger("修改成功").setLogOperType(LogOperEnum.REQ).setKeys("modify","DkBillDtlVO="+JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName()).info();
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("修改对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newLogger("修改对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0099);
        }


        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.newLogger("移除对象").setLogOperType(LogOperEnum.REQ).setKeys("remove",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.dkBillDtlService.removeById(Long.valueOf(id));
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("移除对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newLogger("移除对象失败").setLogOperType(LogOperEnum.REQ).setKeys("modify","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0099);
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("根据主键获取对象").setLogOperType(LogOperEnum.REQ).setKeys("getById",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.newLogger("获取数据,主键不存在").setLogOperType(LogOperEnum.REQ).setKeys("getById","id="+id,CurrentThreadContext.getCurrentUserName()).info();
            return result;
        }

        try {
            DkBillDtlVO vo = this.dkBillDtlService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.newLogger("获取数据,主键不存在").setLogOperType(LogOperEnum.REQ).setKeys("getById","id="+id,CurrentThreadContext.getCurrentUserName()).info();
            }
            result.setData(vo);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("根据主键获取对象失败").setLogOperType(LogOperEnum.REQ).setKeys("getById","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newLogger("根据主键获取对象失败").setLogOperType(LogOperEnum.REQ).setKeys("getById","id="+id,CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0099);
        }

        return result;
    }
    
    
    /**
     * 推送测试问卷
     * 		1、获取项目下  》 支付表下 》 所有的逾期数据 
     * @param request
     * @param response
     * @return
     * @throws BaseException
     */
	@RequestMapping(value = "/pushQuestionnaire.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object pushQuestionnaire(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String billId = request.getParameter("billId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(billId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		
		result = this.dkBillDtlService.addAndpushQuestionnaire(new Long(billId));
		return result;
	}

    /**
     * 推送合同
     * @param billId
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/pushContract.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object pushContract(String billId) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if(StringUtils.isEmpty(billId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            return result;
        }

        result = this.dkBillDtlService.pushContract(new Long(billId));
        return result;
    }

    /**
     * 更新垫款测算结果
     */
    @RequestMapping(value = "/updateCalcrstCd.do", method = {RequestMethod.GET})
    @ResponseBody
    public DataResultDTO updateCalcrstCd(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("更新测算结果").setLogOperType(LogOperEnum.REQ).setKeys("updateCalcrstCd",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        String billId = request.getParameter("billId");
        DataResultDTO result=new DataResultDTO(""+BaseConstant.IS_YESNO_YES,"处理成功");
        String ids = request.getParameter("ids");
        if(StringUtils.isEmpty(billId)){
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("垫款单不能为空!");
            return result;
        }
        try{
            result = this.dkBillDtlService.updateCalcrstCd(billId);
        } catch (BaseException ex) {
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        } catch (Exception ex) {
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }
        return result;
    }
    
    
    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDkBillDtlDetail.do", method = {RequestMethod.GET})
    public ModelAndView toDkBillDtlDetail(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("toDkBillDtlDetail",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlDetail");
        String billId = request.getParameter("billId");
        if(StringUtils.isNotEmpty(billId)){
            DkBillInfoVO dkBillInfoVO = dkBillInfoService.selectById(Long.valueOf(billId));
            DkRuleInfoVO dkRuleInfoVO = dkRuleInfoService.selectById(dkBillInfoVO.getRuleId());
            view.addObject("dkBillInfoVO",dkBillInfoVO);
            view.addObject("dkRuleInfoVO",dkRuleInfoVO);

        }
        return view;
    }
    
    /**
     * 到详情列表页面
     */
    @RequestMapping(value = "/toListPageDetail.do", method = {RequestMethod.GET})
    public ModelAndView toListPageDetail(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("加载列表页面").setLogOperType(LogOperEnum.REQ).setKeys("toListPage",this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName()).info();
        ModelAndView view = new ModelAndView("dk/dkBillDtl/dkBillDtlListDetail");
        String billId = request.getParameter("billId");
        view.addObject("billId",billId);

        List<String> codeGrpCdList = new ArrayList<>();
        codeGrpCdList.add(DkBillDtlConstant.CALC_RST_CD);//垫款单明细-垫款测算结果
        codeGrpCdList.add(DkBillDtlConstant.DTL_STS_CD);//垫款单明细-垫款明细状态
        codeGrpCdList.add(DkQuestneLogConstant.GROUP_CD_QTN_RST_CD);//问卷结果
        codeGrpCdList.add(DkContractLogConstant.SIGN_STS_CD);//合同签署状态
        Map<String, List<KeyValueVO>> stsCdList = sysDictionaryService.getMultiKvList(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
        view.addObject("stsCdList",stsCdList);
        return view;
    }

    /**
     * 执行垫款
     * @param request
     * @param response
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/doDk.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object doDk(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultDTO result=new DataResultDTO(""+BaseConstant.IS_YESNO_YES,"处理成功");
        String ids = request.getParameter("ids");
        if(StringUtils.isEmpty(ids)){
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("执行垫款,垫款明细id不能为空");
            return result;
        }
        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
        DkBillDtlQC dkBillDtlQC = new DkBillDtlQC();
        dkBillDtlQC.setIdList(idsList);
        try{
            result = this.dkBillDtlService.doDk(dkBillDtlQC);
        } catch (BaseException ex) {
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        } catch (Exception ex) {
            result.setCode(""+BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }
        return result;
    }

    /**
     * 执行明垫
     * @return
     */
    @RequestMapping("doMingDian.do")
    @ResponseBody
    public DataResultVO doMingDian(String paySchIds,Long billId,Long ruleId){
        DataResultVO result= new DataResultVO();
        List<Long> paySchIdList = JSON.parseArray(paySchIds, Long.class);
        try {
            // 防止重复分解
            DkBillInfoVO dkBillInfoVO = this.dkBillInfoService.selectById(billId);
            if(dkBillInfoVO!=null && dkBillInfoVO.getBillStsCd().equals("0")){
                throw new BaseException("已经执行完毕");
            }
            DataResultDTO dataResultDTO = this.dkBillDtlService.doMingDian(paySchIdList,ruleId,billId);
            result.setSuccess(dataResultDTO.getSuccess());
            result.setInfo(dataResultDTO.getInfo());
        }catch (BaseException e){
            result.setSuccess(0);
            result.setInfo(e.getMessage());
            BaseLogUtils.newLogger("执行明垫").setLogOperType(LogOperEnum.REQ).setKeys("doMingDian",CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0099);

        }
        return result;
    }
    /**
     * 只导出赎回的数据 
     * @Title: exportBillDtlExcel
     * @param @param qc
     * @param @param request
     * @param @param response
     * @param @return
     * @param @throws Exception
     * @author gaoyongfei
     * @date 2018-6-22 上午10:42:16
     * @return Object 
     * @throws
     */
	@RequestMapping(value = "/exportBillDtlExcel.do", method = {RequestMethod.GET , RequestMethod.POST })
	@ResponseBody
	public Object exportExcel(DkBillDtlQC qc,HttpServletRequest request,HttpServletResponse response) throws Exception {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"导出成功");
		String currentPage = "1";
		String pageSize = "999999";
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        qc.setCalcRstCd(DkBillDtlConstant.CALC_RST_CD_2); // 只导出赎回的数据 
        if (StringUtils.isEmpty(qc.getQtnRstCd().trim())) {
            qc.setQtnRstCd("");
        }
        if (StringUtils.isEmpty(qc.getCalcRstCd().trim())) {
            qc.setCalcRstCd("");
        }
        if (StringUtils.isEmpty(qc.getSignStsCd().trim())) {
            qc.setSignStsCd("");
        }
        if (StringUtils.isEmpty(qc.getDtlStsCd().trim())) {
            qc.setDtlStsCd("");
        }
		page.setCondition(qc);
		
		Pager pager = this.dkBillDtlService.searchListPage(page);
		List<DkBillDtlDTO> list = (List<DkBillDtlDTO>) pager.getResultList();
		List<DkBillDtlVO> listVos = new ArrayList<DkBillDtlVO>();
		if(CollectionUtils.isNotEmpty(list)){
			listVos.addAll(DkBillDtlVOTransform.toVOList(list));
        }
		if(CollectionUtils.isEmpty(listVos)){
        	DkBillDtlVO vo = new DkBillDtlVO();
        	vo.setQtnRstCd("没有可赎回的数据！");
        	listVos.add(vo);
        }
		
		try {
			List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
			String filename="dk_bill_dtl.xlsx";
			ExportParams params = new ExportParams(null, null,ExcelType.XSSF);
			params.setTitleHeight((short) 5);
	        params.setColor(HSSFColor.LIGHT_TURQUOISE.index2);//表头颜色
	        params.setHeaderColor(HSSFColor.WHITE.index);//间隔颜色-未启用
			Workbook wb = ExcelExportUtil.exportExcel(params,DkBillDtlVO.class,listVos);
			response.setHeader("Content-disposition", filename);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="+ filename);
			response.setHeader("Pragma", "No-cache");
			OutputStream ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception e) {
            BaseLogUtils.newLogger("导出文件异常").setLogOperType(LogOperEnum.REQ).setKeys("exportExcel",CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0003);

        }
		return result;
	} 
    
}

